package lib;

import java.io.*;
import java.net.*;
import java.util.*;

import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
import com.thoughtworks.xstream.*;

/**
 * ** Program to get the details of the books you have borrowed. Currently only
 * support student IDs as usernames; however, there are three types of
 * usernames: sID, bar ID(?), and e-mail.
 * 
 * @author smy
 * @version beta2
 **/
public class MyLib {
	private static final String loginurl = "http://202.119.47.8:8080/reader/redr_verify.php";
	private static final String listurl = "http://202.119.47.8:8080/reader/book_lst.php";
	private String userID;
	private String password;
	private ArrayList<BorrowedBook> books = new ArrayList<BorrowedBook>();
	private WebClient wc = new WebClient(BrowserVersion.INTERNET_EXPLORER_8);
	private XStream xs = new XStream();

	/**
	 * Program's entrypoint. One must use two strings as the parameters to get
	 * it going.
	 * 
	 * @category Entrypoint
	 * @param args
	 *            args[2]: username,password
	 * @throws IOException
	 */
	public static void main(String[] args) {
		MyLib test = new MyLib();
		// Check if the inputs are correct
		if (args.length != 2) {
			System.err.println("Invaild inputs. Shutting down.");
			System.exit(1);
		} else {
			test.userID = args[0];
			test.password = args[1];
			try {
				test.go();
			} catch (Exception ex) {
				System.err.println("An error occured");
				System.exit(1);
			}
		}
	}

	/**
	 * @category Internal method
	 * @throws Exception
	 */
	private void go() throws Exception {
		WebRequest wr = new WebRequest(new URL(loginurl), HttpMethod.POST);
		wr.setRequestBody("number=" + userID + "&passwd=" + password
				+ "&select=cert_no&returnURL=");
		wc.setJavaScriptEnabled(false);
		wc.setCssEnabled(false);
		Page wp = wc.getPage(wr);
		if (!wp.getUrl().toString().contains("cust_result")) {
			System.err.println("Username or password is incorrect");
			System.exit(1);
		}
		HtmlPage wp2 = wc.getPage(listurl);
		HtmlTable ht = (HtmlTable) (wp2.getElementsByTagName("table").get(0));
		int k = 1;
		while (k < ht.getRowCount()) {
			String reqID = ht.getRow(k).getCell(0).asText();
			String title = ht.getRow(k).getCell(1).asText();
			String author = ht.getRow(k).getCell(2).asText();
			String date1 = ht.getRow(k).getCell(3).asText();
			String date2 = ht.getRow(k).getCell(4).asText();
			String location = ht.getRow(k).getCell(5).asText();
			books.add(new BorrowedBook(k, reqID, title, author, date1, date2,
					location));
			k++;
		}
		int j = 0;
		FileOutputStream fs = new FileOutputStream("d:/BSWD/" + j + ".xml");
		xs.toXML(books, fs);
	}
}
